<?php

namespace App\Jobs;

use App\Models\User\WxUser;
use App\Models\User\WxUserExperience;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;

class ExperienceExpireCleanJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $rows = WxUserExperience::where('created_at', '<', now()->subHours(6))->delete();
        if($rows){
            $experiences = DB::table('wx_user_experience')->get(['user_id', 'type', 'num', 'created_at']);
            if($experiences && $experiences->isNotEmpty()){
                DB::table('wx_user_experience')->delete();
                DB::statement('ALTER TABLE wx_user_experience AUTO_INCREMENT = 1');
                // 重新插入数据
                foreach ($experiences as $experience) {
                    DB::table('wx_user_experience')->insert([
                        'user_id' => $experience->user_id,
                        'type' => $experience->type,
                        'num' => $experience->num,
                        'created_at' => $experience->created_at,
                        // 如果你的表包括updated_at，确保也将其添加
                        'updated_at' => $experience->updated_at ?? now()
                    ]);
                }
            }
        }

        $the_test_user_id = WxUser::where('phone', '18345678910')->value('id');
        if($the_test_user_id > 0){
            update_user_meta($the_test_user_id, 'experience', 0, 'n');
        }

        _logger_(__file__, __line__, '清理'.$rows.'条用户经验记录');
    }
}
